package srvbiz

import (
	"cloud_worm/util/proto/ujson"
	"cloud_worm/access/server/client"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"cloud_worm/util/unet/usocket"
	"cloud_worm/access/server/rpcclient"
	"cloud_worm/util/proto/urpc"
	"github.com/golang/glog"
)

type MsgVersion struct {
}

func (v *MsgVersion) Deal(agent *client.Agent, data []byte) {

	var msg ujson.MsgVersion
	if err := msg.UnmarshalJSON(data); err != nil {
		glog.Errorf("version msg Unmarshal error: %s", err.Error())
		return
	}

	err := v.handleVersion(agent, &msg)
	if err != nil {
		glog.Errorf("handle version msg error: %s", err.Error())
		return
	}
	return
}

func (v *MsgVersion) handleVersion(agent *client.Agent, msg *ujson.MsgVersion) error {
	wormId := &dbmanager.WormId{}

	if err := wormId.SetAgentOnline(agent.IP, msg.Version, msg.Platform, usocket.TlsServerInstance().Addr,
		agent.Id); err != nil {
		return err
	}

	// 设置该ip的其他记录为无效记录
	if err := wormId.SetInvalidAgentId(agent.IP, agent.Id); err != nil {
		return err
	}

	postData := &rpcclient.AgentEvent{
		EventType: urpc.AgentEventOnline,
		AgentId: agent.Id,
		AgentIP: agent.IP,
		Version: agent.Version,
		NeedAgain: true,
	}
	rpcclient.PushClient.PushOneC <- postData

	return nil
}